﻿/*
 * Created by SharpDevelop.
 * User: matsu
 * Date: 5/20/2010
 * Time: 10:19 PM
 * 
 * Copyright (c) 2010 Matthew MacGregor
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
using System;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
using System.Configuration;
using System.IO;
using System.Reflection;

namespace webui
{
   public class PortUnavailableException: System.Exception
   {
        // The default constructor needs to be defined
        // explicitly now since it would be gone otherwise.
    
        public PortUnavailableException(){}
    
        public PortUnavailableException(string message): base(message) {}
   }
    
    
	/// <summary>
	/// Class with program entry point.
	/// </summary>
	internal sealed class Program
	{
		/// <summary>
		/// Program entry point.
		/// </summary>
		[STAThread]
		private static void Main(string[] args)
		{
			//Set the working directory to the path of the webui executable.
			Directory.SetCurrentDirectory( Application.StartupPath );
			
			
			try //catch all unexpected errors and display a message
			{
				//try to load settings from the .config file
				if ( ! LoadSettings() ) 
				{
					// LoadSettings() writes a new config file with defaults.
		    		// Warn the user that the config file wasn't found, then exit.
		    		MessageBox.Show( "This application requires a configuration file which was not found.   \n"+ 
		    		                 "We will attempt to write a new configuration file with default values.\n" +
		    		                 " \n" +
		    		                 "You may need to adjust these settings manually or reinstall the application.\n" +
		    		                 "\n" );
		    		//if not, create it
					if( ! CreateSettingsFile() )
					{
						//Failing to create the settings file will 
						MessageBox.Show("Unable to create a default configuration file.");
						
					}
		    		Application.Exit();
		    		Thread.Sleep(1000);
		    		// Restart the app
		    		//System.Diagnostics.Process.Start(Application.ExecutablePath);
				}
	  			else
	  			{
					Application.EnableVisualStyles();
					Application.SetCompatibleTextRenderingDefault(false);
					Application.Run(new MainForm());
	  			}
			}catch ( Exception e )
			{
				MessageBox.Show("Oops!  There has been an unexpected error!\n" +
				                e.Message );
			}
			
		}
		
		//Checks if a settings .config file exists
		private static bool CheckSettingsFile()
		{
			bool settingsExist = false;
			try
			{
				System.Configuration.Configuration config =
					ConfigurationManager.OpenExeConfiguration(
						ConfigurationUserLevel.None);
				
				if ( config.HasFile )
				{
					settingsExist = true;
				}
				else
				{
					settingsExist = false;
				}
			} catch
			{
				//no config file
				settingsExist = false;
			}
			return settingsExist;
		}
		
		//Attempts to recreate the configuration file for the application.
		private static bool CreateSettingsFile()
		{
			Assembly _assembly;
   			StreamReader _textStreamReader;   				
            TextWriter tw; 
   			bool success;
   			
			try
   			{
      			_assembly = Assembly.GetExecutingAssembly();
      			_textStreamReader = new StreamReader(
      				_assembly.GetManifestResourceStream("webui.app.config"));
      			tw = new StreamWriter(_assembly.Location + ".Config", true);
      			
      			while(_textStreamReader.Peek() != -1)
      			{
					
            		// write a line of text to the file
            		tw.WriteLine(_textStreamReader.ReadLine());


      			}
      			// close the stream
            	tw.Close();
      			success = true;
   			}
   			catch
   			{
      			success = false;
   			}
   			
   			return success;
		}
		
		//Loads application settings from a .config file
		private static bool LoadSettings()
		{
			bool success = true;
			//Check if the settings file exists
			if ( ! CheckSettingsFile() )
			{

				success = false;
			}
			return success;
			
		}
		
		
		
	}
}
